//
//  Manager+IO.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/16.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation
import SPDatastorage

extension Manager.IO: IOProtocol {
    /// 写入内存并同步到磁盘
    /// - Parameter element: 待添加元素
    public static func writeWallet(_ account: Account, wallet: Wallet) {
//        wallet.accounts.append(account)
//        Manager.shared.wallets?[wallet.path] = wallet
        
        //// 去掉本次存储
//        if wallet.insertOrReplace() {
//            print("写入成功")
//        } else {
//            print("写入失败")
//        }
    }
    
    /// 从磁盘读取钱包并写入内存
    /// - Parameter cls: 读取对象类型
    public static func updatedWallet<Objc: Wallet>(_: Objc.Type, key: String?) -> Objc? {
        guard let key = key, let wallet = Objc.getObject(where: Objc.Properties.path.like(key)) else { return nil }
        wallet.didLoad()
        Manager.shared.wallets?[wallet.path] = wallet
        return wallet
    }
    
    /// 从磁盘读取所有钱包对象并写入内存
    /// - Parameter cls: 读取对象类型集合
    public static func readAllWallets<Objc: Wallet>(_ cls: Objc.Type...) -> [Objc]? {
        guard let wallets = Objc.getObjects() else { return nil }
        var list: [String: Wallet] = [:]
        _ = wallets.map {list[$0.path] = $0}
        for (_, wallet) in list {
            wallet.didLoad()
        }
        Manager.shared.wallets = list
        return wallets
    }
    
    public static func cacheWallet(_ wallet: Wallet) {
        wallet.didLoad()
    }
}
